package com.lilicould.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter({"/admin.jsp","/register/employee"})
public class AdminFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("accountType") == null) {
            // 用户未登录，跳转到登录页面
            request.setAttribute("error", "请先登录");
            request.getRequestDispatcher("/page/err.jsp").forward(request, response);
        }else if (!session.getAttribute("accountType").equals("admin")) {
            request.setAttribute("error", "您没有权限访问此页面");
            request.getRequestDispatcher("/page/err.jsp").forward(request, response);
        }else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("我被初始化了");
    }

    @Override
    public void destroy() {
        System.out.println("我被销毁了");
    }
}
